<template>
  <div class="users-list-container">
    <div class="page-header">
      <h2>用户账单列表</h2>
      <div class="header-actions">
        <el-input
            v-model="searchQuery"
            placeholder="搜索..."
            prefix-icon="Search"
            class="search-input"
            clearable
        />
        <el-button type="primary" @click="fetchData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <div class="table-card">
      <a-table
          :columns="columns"
          :data-source="filteredData"
          :loading="loading"
          :pagination="{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`
        }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'total_fee'">
            <span class="fee-cell">¥{{ record.total_fee }}</span>
          </template>
          <template v-if="column.dataIndex === 'charge_amount'">
            <span class="amount-cell">{{ record.charge_amount }} kWh</span>
          </template>
          <template v-if="column.dataIndex === 'charge_duration'">
            <span class="duration-cell">{{ record.charge_duration }}</span>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script>
import { reactive, ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'

export default {
  components: {
    Search,
    Refresh
  },
  setup() {
    const loading = ref(false)
    const searchQuery = ref('')

    const columns = [
      {
        title: '车辆ID',
        dataIndex: 'car_id',
        width: 120,
        fixed: 'left'
      },
      {
        title: '日期',
        dataIndex: 'date',
        width: 120
      },
      {
        title: '账单ID',
        dataIndex: 'bill_id',
        width: 120
      },
      {
        title: '充电桩ID',
        dataIndex: 'pile_id',
        width: 120
      },
      {
        title: '充电量',
        dataIndex: 'charge_amount',
        width: 120
      },
      {
        title: '充电时长',
        dataIndex: 'charge_duration',
        width: 120
      },
      {
        title: '开始时间',
        dataIndex: 'start_time',
        width: 180
      },
      {
        title: '结束时间',
        dataIndex: 'end_time',
        width: 180
      },
      {
        title: '充电费用',
        dataIndex: 'total_charge_fee',
        width: 120
      },
      {
        title: '服务费用',
        dataIndex: 'total_service_fee',
        width: 120
      },
      {
        title: '合计费用',
        dataIndex: 'total_fee',
        width: 120,
        fixed: 'right'
      }
    ]

    const dataSource = reactive([])

    const filteredData = computed(() => {
      if (!searchQuery.value) return dataSource

      const query = searchQuery.value.toLowerCase()
      return dataSource.filter(item =>
          Object.values(item).some(val =>
              String(val).toLowerCase().includes(query)
          )
      )
    })

    // 工具函数：将秒数转为"xx分钟xx秒"
    function formatDuration(seconds) {
      const min = Math.floor(seconds / 60)
      const sec = seconds % 60
      if (min > 0) {
        return `${min}分钟${sec}秒`
      } else {
        return `${sec}秒`
      }
    }

    const fetchData = async () => {
      loading.value = true
      try {
        dataSource.length = 0
        const response = await axios.get(process.env.VUE_APP_BACKEND_URL + '/user/checkBill?car_id=' + localStorage.getItem('car_id'))
        const { data } = response.data
        // 格式化bill_id、pile_id、charge_duration
        const formattedData = data.bills.map(bill => ({
          ...bill,
          bill_id: Array.isArray(bill.bill_id) ? bill.bill_id.join(', ') : String(bill.bill_id ?? ''),
          pile_id: Array.isArray(bill.pile_id) ? bill.pile_id.join(', ') : String(bill.pile_id ?? ''),
          charge_duration: formatDuration(bill.charge_duration),
          start_time: new Date(bill.start_time).toLocaleString(),
          end_time: new Date(bill.end_time).toLocaleString()
        }))
        dataSource.push(...formattedData)
        ElMessage.success('数据加载成功')
      } catch (error) {
        console.error(error)
        ElMessage.error('数据加载失败')
      } finally {
        loading.value = false
      }
    }

    onMounted(fetchData)

    return {
      columns,
      dataSource,
      loading,
      searchQuery,
      filteredData,
      fetchData
    }
  }
}
</script>

<style scoped>
.users-list-container {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  color: var(--primary-color);
  font-size: 24px;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 16px;
}

.search-input {
  width: 240px;
}

.table-card {
  min-width: 1200px;
  background: white;
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-md);
  padding: 24px;
  transition: all var(--transition-normal);
}

.table-card:hover {
  box-shadow: var(--shadow-lg);
}

:deep(.ant-table-thead > tr > th) {
  background: var(--gradient-primary) !important;
  color: white !important;
  font-weight: 500;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: rgba(43, 51, 145, 0.05) !important;
}

.fee-cell {
  color: #f56c6c;
  font-weight: 500;
}

.amount-cell {
  color: var(--primary-color);
  font-weight: 500;
}

.duration-cell {
  color: #67c23a;
  font-weight: 500;
}

:deep(.ant-pagination-item-active) {
  background: var(--primary-color) !important;
  border-color: var(--primary-color) !important;
}

:deep(.ant-pagination-item-active a) {
  color: white !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .users-list-container {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-actions {
    flex-direction: column;
  }

  .search-input {
    width: 100%;
  }
}
</style>
  
